package com.go.where.manager.action.go;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.InterceptorRefs;
import org.json.simple.JSONObject;

import com.go.where.manager.action.SuperAction;
import com.go.where.manager.common.Constants;
import com.go.where.manager.exception.ManagerException;
import com.go.where.manager.freemarker.CustomFreemarkerManager;
import com.go.where.manager.http.HttpClient;
import com.go.where.manager.page.Pagination;
import com.go.where.manager.pojo.ActivityInfo;
import com.go.where.manager.pojo.BigClassInfo;
import com.go.where.manager.pojo.SmallClassInfo;
import com.go.where.manager.pojo.user.OperatorInfo;
import com.go.where.manager.service.ActivityService;
import com.go.where.manager.service.BigClassService;
import com.go.where.manager.service.SmallClassService;
import com.go.where.manager.service.system.OperatorService;
import com.go.where.manager.util.CommonUtil;
import com.go.where.manager.util.CompressPicUtil;
import com.go.where.manager.util.DateUtil;
import com.go.where.manager.util.KindEditUtil;

@InterceptorRefs( {
		@InterceptorRef(value = "defaultStack", params = { "maximumSize",
				"2048000", "allowedTypes",
				"image/bmp,image/png,image/gif,image/jpeg" }),
		@InterceptorRef(value = "defalutStackSet") })
public class ActivityAction extends SuperAction {

	/**
	 * 
	 */
	private static final long serialVersionUID = 4383195694100314090L;
	private static final Logger log = Logger.getLogger(ActivityAction.class);

	public Pagination<?> page;

	@Resource(name = "activityService")
	private ActivityService activityService;
	@Resource(name = "bigClassService")
	private BigClassService bigClassService;
	@Resource(name = "smallClassService")
	private SmallClassService smallClassService;
	@Resource
	private OperatorService operatorService;

	private ActivityInfo activityInfo;
	private ActivityInfo activityInfoQuery;

	private List<BigClassInfo> bigClassList;
	private List<SmallClassInfo> smallClassList;

	private String activityId;
	private String top;
	private String bigClassId;
	private String smallClassId;

	private File preActivityPhoto;// 上传的文件
	private String preActivityPhotoFileName; // 文件名称
	private String preActivityPhotoContentType; // 文件类型

	private File signupPhoto;// 上传的文件
	private String signupPhotoFileName; // 文件名称
	private String signupPhotoContentType; // 文件类型

	/**
	 * 查询列表
	 * 
	 * @return
	 */
	public String list() {
		if (activityInfoQuery == null) {
			activityInfoQuery = new ActivityInfo();
			activityInfoQuery.setPageSize(Constants.INIT_PAGESIZE);
			activityInfoQuery.setCurrentPage(Constants.INIT_CURRENTPAGE);
		}
		try {
			String userId = getCurrentOperator().getUserId();
			OperatorInfo op = operatorService.queryOperatorInfoByUserId(userId);
			if (op != null) {
				String roleId = op.getRoleId();
				if (CustomFreemarkerManager.getValue("system.merchant.role.id")
						.equals(roleId)) {
					activityInfoQuery.setMroleId(roleId);
				}
			}
			activityInfoQuery.setIsDelete(Constants.NOT_DELETED);
			page = activityService.queryPage(activityInfoQuery);
		} catch (Exception e) {
			addActionError(e.getMessage());
			log.error("查询信息异常", e);
		}
		return LIST;
	}

	public String add() {
		OperatorInfo op = operatorService
				.queryOperatorInfoByUserId(getCurrentOperator().getUserId());
		String mroleId = null;
		if (op != null) {
			String roleId = op.getRoleId();
			if (CustomFreemarkerManager.getValue("system.merchant.role.id")
					.equals(roleId)) {
				mroleId = roleId;
			}
		}
		BigClassInfo bi = new BigClassInfo();
		bi.setMroleId(mroleId);
		bigClassList = bigClassService.queryAll(bi);
		return INPUT;
	}

	/**
	 * 获取某一大类下的所有小类
	 * 
	 * @return
	 */
	public String getSmallClasses() {
		OperatorInfo op = operatorService
				.queryOperatorInfoByUserId(getCurrentOperator().getUserId());
		String mroleId = null;
		if (op != null) {
			String roleId = op.getRoleId();
			if (CustomFreemarkerManager.getValue("system.merchant.role.id")
					.equals(roleId)) {
				mroleId = roleId;
			}
		}
		SmallClassInfo small = new SmallClassInfo();
		small.setBigClass(bigClassId);
		small.setMroleId(mroleId);
		List<SmallClassInfo> list = smallClassService.queryByBigClass(small);
		message = CommonUtil.gson().toJson(list);
		return "ajax";
	}

	public String getSmallClassDetail() {
		SmallClassInfo sci = smallClassService.queryByPrimartKey(smallClassId);
		if (sci != null) {
			message = CommonUtil.gson().toJson(sci);
		}
		return "ajax";
	}

	/**
	 * 保存
	 * 
	 * @return
	 */
	public String save() {
		try {
			HttpServletRequest request = ServletActionContext.getRequest();
			String savePath = ServletActionContext.getServletContext()
					.getRealPath(CommonUtil.FILE_SEPARATOR)
					+ Constants.MATERIAL_HTML;
			File htmlPath = new File(savePath);
			if (!htmlPath.exists()) {
				htmlPath.mkdirs();
			}
			SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
			String newFileName = df.format(new Date()) + "_"
					+ new Random().nextInt(1000) + ".html";
			String materialUrlPrefix = CustomFreemarkerManager
					.getValue("url.prefix");
			String htmlData = request.getParameter("content") != null ? request
					.getParameter("content") : "";
			log.info("获取富文本编辑器中内容：" + htmlData);
			htmlData = htmlData.replaceAll(Constants.PROJECT_NAME,
					materialUrlPrefix + Constants.PROJECT_NAME);
			log.info("替换后的内容：" + htmlData);
			StringBuilder sb = KindEditUtil.linkHtml(htmlData, "", true);

			CommonUtil.createHtml(sb.toString(), savePath + newFileName);

			activityInfo.setActivityContent(materialUrlPrefix
					+ Constants.PROJECT_NAME + CommonUtil.FILE_SEPARATOR
					+ Constants.MATERIAL_HTML + newFileName);

			String previewRealpath = ServletActionContext.getServletContext()
					.getRealPath(
							CommonUtil.FILE_SEPARATOR
									+ Constants.ACTIVITY_PREVIEW_IMAGES);
			String signupRealpath = ServletActionContext.getServletContext()
					.getRealPath(
							CommonUtil.FILE_SEPARATOR
									+ Constants.ACTIVITY_SIGNUP_IMAGES);
			// 上传活动预览图
			uploadPicture(activityInfo, preActivityPhoto,
					preActivityPhotoFileName, previewRealpath, true);
			// 上传活动报名页大图
			uploadPicture(activityInfo, signupPhoto, signupPhotoFileName,
					signupRealpath, false);
			if(activityInfo!=null){
				if(StringUtils.isBlank(activityInfo.getIsTop())){
					activityInfo.setIsTop("0");
				}
				if (StringUtils.isBlank(activityInfo.getIsLimitTime())) {
					activityInfo.setIsLimitTime("0");
				}
			}
			activityService.save(activityInfo, getCurrentOperator());
			redirectionUrl = "activity!list.htm";
			return SUCCESS;
		} catch (Exception e) {
			log.error("保存信息异常", e);
			addActionError("保存信息异常！" + e);
			return this.add();
		}
	}

	public String toEdit() {
		try {
			activityInfo = activityService.queryByPrimartKey(activityId);
			OperatorInfo op = operatorService
					.queryOperatorInfoByUserId(getCurrentOperator().getUserId());
			String mroleId = null;
			if (op != null) {
				String roleId = op.getRoleId();
				if (CustomFreemarkerManager.getValue("system.merchant.role.id")
						.equals(roleId)) {
					mroleId = roleId;
				}
			}
			BigClassInfo bi = new BigClassInfo();
			bi.setMroleId(mroleId);
			bigClassList = bigClassService.queryAll(bi);
			SmallClassInfo small = new SmallClassInfo();
			small.setClassId(activityInfo.getBigClassId());
			smallClassList = smallClassService.queryByBigClass(small);
			activityInfo.setActivityContentUrl(activityInfo
					.getActivityContent());
			String htmlUrl = activityInfo.getActivityContent();
			String ip = CustomFreemarkerManager.getValue("ip.url.prefix");
			if (StringUtils.isNotBlank(ip) && StringUtils.isNotBlank(htmlUrl)) {
				htmlUrl = htmlUrl.replace(CustomFreemarkerManager.getValue(
						"ip.url.prefix.common").trim(), ip.trim());
			}
			HttpClient hc = new HttpClient();
			String htmlContent = "";
			if (StringUtils.isNotBlank(htmlUrl)) {
				htmlContent = hc.doGet(htmlUrl, "utf-8");
			}
			String[] htmls = null;
			if (StringUtils.isNotBlank(htmlContent)) {
				htmls = htmlContent.split("<body>");
				if (htmls.length > 1) {
					String bodyHtmlStr = htmls[1];
					if (StringUtils.isNotBlank(bodyHtmlStr)) {
						String[] bodyHtmls = bodyHtmlStr.split("</body>");
						String body = bodyHtmls[0];
						activityInfo.setActivityContent(this
								.htmlspecialchars(body));
					}
				}
			}
		} catch (Exception e) {
			addActionError("查询信息异常" + e.getMessage());
			log.error("查询信息异常", e);
		}
		return INPUT;
	}

	/**
	 * 编辑
	 * 
	 * @return
	 */
	public String edit() {
		try {
			HttpServletRequest request = ServletActionContext.getRequest();
			String savePath = ServletActionContext.getServletContext()
					.getRealPath(CommonUtil.FILE_SEPARATOR)
					+ Constants.MATERIAL_HTML;
			String newFileName = "";
			if (StringUtils.isBlank(activityInfo.getActivityContentUrl())) {
				File htmlPath = new File(savePath);
				if (!htmlPath.exists()) {
					htmlPath.mkdirs();
				}
				SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
				newFileName = df.format(new Date()) + "_"
						+ new Random().nextInt(1000) + ".html";
			} else {

				String[] htmlArr = activityInfo.getActivityContentUrl().split(
						"/");
				newFileName = htmlArr[htmlArr.length - 1];
			}
			String materialUrlPrefix = CustomFreemarkerManager
					.getValue("url.prefix");
			String htmlData = request.getParameter("content") != null ? request
					.getParameter("content") : "";
			log.info("获取富文本编辑器中内容：" + htmlData);
			htmlData = htmlData.replaceAll(Constants.PROJECT_NAME,
					materialUrlPrefix + Constants.PROJECT_NAME);
			log.info("替换后的内容：" + htmlData);
			StringBuilder sb = KindEditUtil.linkHtml(htmlData, activityInfo
					.getActivityTitle(), false);

			CommonUtil.createHtml(sb.toString(), savePath + newFileName);

			activityInfo.setActivityContent(materialUrlPrefix
					+ Constants.PROJECT_NAME + CommonUtil.FILE_SEPARATOR
					+ Constants.MATERIAL_HTML + newFileName);

			String previewRealpath = ServletActionContext.getServletContext()
					.getRealPath(
							CommonUtil.FILE_SEPARATOR
									+ Constants.ACTIVITY_PREVIEW_IMAGES);
			String signupRealpath = ServletActionContext.getServletContext()
					.getRealPath(
							CommonUtil.FILE_SEPARATOR
									+ Constants.ACTIVITY_SIGNUP_IMAGES);
			// 上传活动预览图
			uploadPicture(activityInfo, preActivityPhoto,
					preActivityPhotoFileName, previewRealpath, true);
			// 上传活动报名页大图
			uploadPicture(activityInfo, signupPhoto, signupPhotoFileName,
					signupRealpath, false);
			if(activityInfo!=null){
				if(StringUtils.isBlank(activityInfo.getIsTop())){
					activityInfo.setIsTop("0");
				}
				if (StringUtils.isBlank(activityInfo.getIsLimitTime())) {
					activityInfo.setIsLimitTime("0");
				}
			}
			activityService.update(activityInfo, getCurrentOperator());
			redirectionUrl = "activity!list.htm";
			return SUCCESS;
		} catch (Exception e) {
			log.error("修改信息异常", e);
			addActionError("修改信息异常！" + e);
			activityId = activityInfo.getActivityId();
			return this.toEdit();
		}
	}

	/**
	 * 上传图片
	 * 
	 * @param activityInfo
	 * @param picture
	 * @param pictureFileName
	 * @throws UnsupportedEncodingException
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	private void uploadPicture(ActivityInfo activityInfo, File picture,
			String pictureFileName, String picRealpath, boolean preOrNot)
			throws UnsupportedEncodingException, FileNotFoundException,
			IOException {
		StringBuilder picPath = new StringBuilder();
		ServletActionContext.getRequest().setCharacterEncoding("UTF-8");
		String realpath = picRealpath;
		File file = picture;
		if (file != null) {
			File savedir = new File(realpath);
			if (!savedir.exists()) {
				savedir.mkdirs();
			}
			String newFileName = DateUtil.format(new Date(), "yyyyMMddHHmmss")
					+ "_" + CommonUtil.createRandomNumber()
					+ pictureFileName.substring(pictureFileName.indexOf("."));
			FileOutputStream fos = new FileOutputStream(realpath
					+ CommonUtil.FILE_SEPARATOR + newFileName);
			if (preOrNot) {
				picPath.append(CommonUtil.FILE_SEPARATOR
						+ Constants.ACTIVITY_PREVIEW_IMAGES);
			} else {
				picPath.append(CommonUtil.FILE_SEPARATOR
						+ Constants.ACTIVITY_SIGNUP_IMAGES);
			}

			picPath.append(Constants.ZOOM_PATH + CommonUtil.FILE_SEPARATOR
					+ newFileName);
			try {
				CompressPicUtil.compressPicture(realpath, newFileName, file);
				FileInputStream fis = new FileInputStream(file);
				byte[] buffer = new byte[1024];
				int len = 0;
				while ((len = fis.read(buffer)) > 0) {
					fos.write(buffer, 0, len);
				}
				fis.close();
				fos.close();
			} catch (Exception e) {
				log.error("", e);
			}
		}

		if (picPath != null && picPath.toString().length() > 0) {
			if (preOrNot) {
				activityInfo.setPrePhotoPath(picPath.toString());
			} else {
				activityInfo.setSignupPhotoPath(picPath.toString());
			}
		}
	}

	/**
	 * 详情
	 * 
	 * @return
	 */
	public String detail() {
		activityInfo = activityService.queryByPrimartKey(activityId);
		OperatorInfo op = operatorService
				.queryOperatorInfoByUserId(getCurrentOperator().getUserId());
		String mroleId = null;
		if (op != null) {
			String roleId = op.getRoleId();
			if (CustomFreemarkerManager.getValue("system.merchant.role.id")
					.equals(roleId)) {
				mroleId = roleId;
			}
		}
		BigClassInfo bi = new BigClassInfo();
		bi.setMroleId(mroleId);
		bigClassList = bigClassService.queryAll(bi);
		SmallClassInfo small = new SmallClassInfo();
		small.setBigClass(activityInfo.getBigClassId());
		smallClassList = smallClassService.queryByBigClass(small);
		return "detail";
	}

	/**
	 * 设置置顶或取消
	 * 
	 * @return
	 */
	public String setTop() {
		activityInfo = new ActivityInfo();
		activityInfo.setActivityId(activityId);
		activityInfo.setIsTop(top);
		try {
			activityService.update(activityInfo, getCurrentOperator());
			redirectionUrl = "activity!list.htm";
			return SUCCESS;
		} catch (Exception e) {
			log.error("置顶信息设置异常", e);
			addActionError("置顶信息设置异常" + e);
			return this.list();
		}
	}

	public String falseDelete() {
		activityInfo = new ActivityInfo();
		activityInfo.setActivityId(activityId);
		activityInfo.setIsDelete(Constants.DELETED);
		try {
			activityService.update(activityInfo, getCurrentOperator());
			redirectionUrl = "activity!list.htm";
			return SUCCESS;
		} catch (Exception e) {
			log.error("删除信息异常", e);
			addActionError("删除信息异常" + e);
			return this.list();
		}
	}

	/**
	 * 富文本编辑器里上传图片
	 * 
	 * @return
	 * @throws FileUploadException
	 * @throws IOException
	 */
	public String imgUpload() throws FileUploadException, IOException {
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpServletResponse response = ServletActionContext.getResponse();
		PrintWriter out = response.getWriter();
		String obj = "";
		try {
			obj = KindEditUtil.uploadImage(request, response, out,
					Constants.ACTIVITY_CONTENT_PATH);
		} catch (ManagerException e) {
			return e.getMessage();
		}
		// log.info(saveUrl);
		// 在编辑框内生成图片
		out.print(obj);
		return null;
	}

	/**
	 * 图片文件管理
	 * 
	 * @return
	 * @throws Exception
	 */
	public String fileManager() throws Exception {
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpServletResponse response = ServletActionContext.getResponse();
		PrintWriter out = response.getWriter();

		JSONObject result = new JSONObject();
		try {
			result = KindEditUtil.fileManager(request, out,
					Constants.ACTIVITY_CONTENT_PATH);
		} catch (ManagerException e) {
			return null;
		}

		response.setContentType("application/json; charset=UTF-8");
		out.println(result.toJSONString());
		return null;
	}

	private String htmlspecialchars(String htmlStr) {
		htmlStr = htmlStr.replaceAll("&", "&amp;");
		htmlStr = htmlStr.replaceAll("<", "&lt;");
		htmlStr = htmlStr.replaceAll(">", "&gt;");
		htmlStr = htmlStr.replaceAll("\"", "&quot;");
		return htmlStr;
	}

	public Pagination<?> getPage() {
		return page;
	}

	public void setPage(Pagination<?> page) {
		this.page = page;
	}

	public String getTop() {
		return top;
	}

	public void setTop(String top) {
		this.top = top;
	}

	public ActivityInfo getActivityInfo() {
		return activityInfo;
	}

	public void setActivityInfo(ActivityInfo activityInfo) {
		this.activityInfo = activityInfo;
	}

	public ActivityInfo getActivityInfoQuery() {
		return activityInfoQuery;
	}

	public void setActivityInfoQuery(ActivityInfo activityInfoQuery) {
		this.activityInfoQuery = activityInfoQuery;
	}

	public List<BigClassInfo> getBigClassList() {
		return bigClassList;
	}

	public void setBigClassList(List<BigClassInfo> bigClassList) {
		this.bigClassList = bigClassList;
	}

	public String getActivityId() {
		return activityId;
	}

	public void setActivityId(String activityId) {
		this.activityId = activityId;
	}

	public List<SmallClassInfo> getSmallClassList() {
		return smallClassList;
	}

	public void setSmallClassList(List<SmallClassInfo> smallClassList) {
		this.smallClassList = smallClassList;
	}

	public String getBigClassId() {
		return bigClassId;
	}

	public void setBigClassId(String bigClassId) {
		this.bigClassId = bigClassId;
	}

	public String getSmallClassId() {
		return smallClassId;
	}

	public void setSmallClassId(String smallClassId) {
		this.smallClassId = smallClassId;
	}

	public File getPreActivityPhoto() {
		return preActivityPhoto;
	}

	public void setPreActivityPhoto(File preActivityPhoto) {
		this.preActivityPhoto = preActivityPhoto;
	}

	public String getPreActivityPhotoFileName() {
		return preActivityPhotoFileName;
	}

	public void setPreActivityPhotoFileName(String preActivityPhotoFileName) {
		this.preActivityPhotoFileName = preActivityPhotoFileName;
	}

	public String getPreActivityPhotoContentType() {
		return preActivityPhotoContentType;
	}

	public void setPreActivityPhotoContentType(
			String preActivityPhotoContentType) {
		this.preActivityPhotoContentType = preActivityPhotoContentType;
	}

	public File getSignupPhoto() {
		return signupPhoto;
	}

	public void setSignupPhoto(File signupPhoto) {
		this.signupPhoto = signupPhoto;
	}

	public String getSignupPhotoFileName() {
		return signupPhotoFileName;
	}

	public void setSignupPhotoFileName(String signupPhotoFileName) {
		this.signupPhotoFileName = signupPhotoFileName;
	}

	public String getSignupPhotoContentType() {
		return signupPhotoContentType;
	}

	public void setSignupPhotoContentType(String signupPhotoContentType) {
		this.signupPhotoContentType = signupPhotoContentType;
	}

}
